//
//  JPMgmtForm.swift
//  ANOA
//
//  Created by 邱仙凯 on 2022/4/8.
//  Copyright © 2025 aowang. All rights reserved.
//

import UIKit

class JPMgmtForm: GlobalFormVC,operatable,refreshable,DateWidgetableOK,BatchSelectable,KSImageUtilDelegate {
    var item1 :KSFormHItem = {
        let appe = KSFormHAppear()
            .roundType(.top)
        let v = KSFormHItem(title: "竞拍编号",appearance:appe)
        v.disabled = true

        return v
    }()
    var item2 :KSFormHItem = {
        let appe = KSFormHAppear()
        let v = KSFormHItem(title: "竞拍标题*",appearance:appe )
         return v
    }()
    var item3 :KSFormHItem = {
        let appe = KSFormHAppear()
         let v = KSFormHItem(title: "单据行业类型*",appearance:appe )
        v.disabled = true

         return v
    }()
    var item4 :KSFormHItem = {
        let appe = KSFormHAppear()
         let v = KSFormHItem(title: "品种名称",appearance:appe )
        v.disabled = true
        return v
    }()
    var item5 :KSFormHItem = {
        let appe = KSFormHAppear()
        let v = KSFormHItem(title: "产品名称*",appearance:appe )
        return v
    }()
    var itemProContract :KSFormHItem = {
        let appe = KSFormHAppear()
        let v = KSFormHItem(title: "产品合同名称",appearance:appe )
        v.disabled = true
        return v
    }()
    var item6 :KSFormHItem = {
        let appe = KSFormHAppear()
            .twoDemiInput(true)
        let v = KSFormHItem(title: "数量(头)*",appearance:appe )
        return v
    }()
    var item7 :KSFormHItem = {
        let appe = KSFormHAppear()
            .twoDemiInput(true)
        let v = KSFormHItem(title: "起拍数量(头)*",appearance:appe )
        return v
    }()
    var item8 :KSFormHItem = {
        let appe = KSFormHAppear()
        let v = KSFormHItem(title: "均重(KG)*",appearance:appe )
        return v
    }()
    var item9 :KSFormHItem = {
        let appe = KSFormHAppear()
        let v = KSFormHItem(title: "计量单位*",appearance:appe )
        return v
    }()
    var itemVway :KSFormHItem = {
        let appe = KSFormHAppear()
        let v = KSFormHItem(title: "计价方式*",appearance:appe )
        v.disabled = true
        return v
    }()
    var item10 :KSFormHItem = {
        let appe = KSFormHAppear()
            .twoDemiInput(true)
        let v = KSFormHItem(title: "起拍价(元)*",appearance:appe )
        return v
    }()
    var itemReference :KSFormHItem = {
        let appe = KSFormHAppear()
            .twoDemiInput(true)
        let v = KSFormHItem(title: "参考价(元)",appearance:appe )
        v.disabled = true
        return v
    }()
    var item11 :KSFormHItem = {
        let appe = KSFormHAppear()
            .twoDemiInput(true)
        let v = KSFormHItem(title: "需缴纳保证金*",appearance:appe )
        return v
    }()
    var item12 :KSFormHItem = {
        let appe = KSFormHAppear()
            .twoDemiInput(true)
        let v = KSFormHItem(title: "竞价幅度(元)*",appearance:appe )
        return v
    }()
    var item13 :KSFormHItem = {
        let appe = KSFormHAppear()
            .twoDemiInput(true)
        let v = KSFormHItem(title: "出价次数*",appearance:appe )
        return v
    }()
    var item14 :KSFormHItem = {
        let appe = KSFormHAppear()
        let v = KSFormHItem(title: "开始时间*",appearance:appe )
        return v
    }()
    var item15 :KSFormHItem = {
        let appe = KSFormHAppear()
        let v = KSFormHItem(title: "结束时间*",appearance:appe )
        return v
    }()
    var item16 :KSFormHItem = {
        let appe = KSFormHAppear()
        let v = KSFormHItem(title: "出栏时间(开始)*",appearance:appe )
        return v
    }()
    var item17 :KSFormHItem = {
        let appe = KSFormHAppear()
        let v = KSFormHItem(title: "出栏时间(结束)*",appearance:appe )
        return v
    }()
    var item18 :KSFormHItem = {
        let appe = KSFormHAppear()
            .contentHight(50)
        let v = KSFormHItem(title: "发布单位*",appearance:appe,type:.tempTextView )
        return v
    }()
    var item19 :KSFormHItem = {
        let appe = KSFormHAppear()
        let v = KSFormHItem(title: "发布猪场*",appearance:appe )
        return v
    }()
    var item20 :KSFormHItem = {
        let appe = KSFormHAppear()
        let v = KSFormHItem(title: "省*",appearance:appe )
        return v
    }()
    var item21 :KSFormHItem = {
        let appe = KSFormHAppear()
        let v = KSFormHItem(title: "城市*",appearance:appe )
        return v
    }()
    var item22 :KSFormHItem = {
        let appe = KSFormHAppear()
            .contentHight(80)
        let v = KSFormHItem(title: "地址*",appearance:appe,type:.tempTextView )
        return v
    }()
    var item23 :KSFormHItem = {
        let appe = KSFormHAppear()
        let v = KSFormHItem(title: "联系人*",appearance:appe )
        return v
    }()
    var item24 :KSFormHItem = {
        let appe = KSFormHAppear()
            .twoDemiInput(true)
        let v = KSFormHItem(title: "联系方式*",appearance:appe )
        return v
    }()
    var item25 :KSFormHItem = {
        let appe = KSFormHAppear()
            .segTitleArr(["启用","禁用"])
        let v = KSFormHItem(title: "启用状态",appearance:appe,type: .segment )
        return v
    }()
    var item26 :KSFormHItem = {
        let appe = KSFormHAppear()
        let v = KSFormHItem(title: "制单人",appearance:appe )
        v.disabled = true
        return v
    }()
    var item27 :KSFormHItem = {
        let appe = KSFormHAppear()
            .segTitleArr(["是","否"])
        let v = KSFormHItem(title: "是否自动成交",appearance:appe,type: .segment )
        return v
    }()
    var item28 :KSFormHItem = {
        let appe = KSFormHAppear()
            .segTitleArr(["是","否"])
            .roundType(.bottom)
        let v = KSFormHItem(title: "是否邀拍",appearance:appe ,type: .segment)
        return v
    }()
    var item29 :KSFormHItem = {
        let appe = KSFormHAppear()
            .contentHight(80)
        let v = KSFormHItem(title: "竞拍说明",appearance:appe,type:.tempTextView )
        return v
    }()
    var sectionx1 :ItemSectionView = {
        let v = ItemSectionView()
        v.lab.text =  "封面"
        v.btn.isHidden = true
         return v
    }()
    var sectionx2 :ItemSectionView = {
        let v = ItemSectionView()
        v.lab.text =  "详情"
        v.btn.isHidden = true
         return v
    }()
    var main = JPMgmtModel(JSON:["":""])!
    var details = [ClientInfo]()
    
    static func initForFix(model:JPMgmtModel) -> JPMgmtForm {
        
        let vc = JPMgmtForm()
        vc.excuteType = .fix
        vc.main = model
        return vc
    }
    static func initForView(model:JPMgmtModel) -> JPMgmtForm {
        
        let vc = JPMgmtForm()
        vc.excuteType = .view
        vc.main = model
        return vc
    }
    static func initForAudit(model:JPMgmtModel) -> JPMgmtForm {
        
        let vc = JPMgmtForm()
        vc.excuteType = .audit
        vc.main = model
        return vc
    }
    static func initForAdd() -> JPMgmtForm {
        
        let vc = JPMgmtForm()
        vc.excuteType = .add
        //          vc.main.mOrgId = USERINFO.mOrgId
        //        vc.main.mOrgNm = USERINFO.mOrgNm
        //        vc.main.auditMark = "0"
        vc.main.zDate = Date.today
        vc.main.zStaffId = USERINFO.idKey.unwrap
        vc.main.zStaffNm = USERINFO.zName.unwrap
        vc.main.zUse = "1"
        vc.main.zInvited = "0"
        vc.main.zAutoZb = "0"

        vc.main.zDepositMoney = "0"

        vc.main.zBeginDate = Date.todayAfter(1) + " 09:00:00"
        vc.main.zEndDate = Date.todayAfter(1) + " 10:00:00"
        vc.main.zDate = Date.todayAfter(1) + " 10:00:00"

        return vc
    }
    
    var attr_main = [VideoImg]()
    var attr_detail = [VideoImg]()

    var imageUtil2:KSImageSelectUtil!
    // 防止外面乱初始化，并提供静态方法给调用者
    private init() {
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.configRightAndTitle()
        
        
      
        
        self.tableVw.register(GlobalSectionHeader.self, forHeaderFooterViewReuseIdentifier: GlobalSectionHeader.identifier)
        tableVw.register(GlobalAddTableCell.self, forCellReuseIdentifier: GlobalAddTableCell.identifier)
        
        self.tableVw.register(JPMgmtFormCell.self, forCellReuseIdentifier: JPMgmtFormCell.identifier)
        
        if excuteType == .fix || excuteType == .view || excuteType == .audit {
            
            KSNetwork.shared.doRequest(API.homepage(.JPMg_getJpInfoForm(id_key: self.main.idKey.unwrap))) { (data:BaseResultOK<JPMgmtModel>) in
                if data.flag == TRUE {
                    if let info = data.infoObjCombine {
                        self.main = info
                        if let dets = info.clientInfo {
                            self.details = dets
                        }
                        if let picA = info.picInfo {
                            self.attr_main.removeAll()
                            self.attr_detail.removeAll()

                            for item in picA {
                                var ttt:SourType = .file
                                if item.zType == "图片" {
                                    ttt = .image
                                } else if item.zType == "视频" {
                                    ttt = .video
                                }
                                var one = VideoImg(type: ttt, idkey: item.idKey.unwrap, url: configURLOK(latter: item.zPicUrl.unwrap), name: item.zName.unwrap)
                                if ttt == .image {
                                    one.image = getPicture(url: one.url.unwrap)
                                }
                                if item.zMain == "是" {
                                    self.attr_main.append(one)
                                } else {
                                    self.attr_detail.append(one)
                                }
                                
                            }
 
                            self.configView()
                            self.configAction()
                            self.configDataSource()
                            self.tableVw.reloadData()
                        }
 
                    }
                    
                } else {
                    KSToast(data.errorCombine.unwrap)
                }
            }
        } else {
            configView()
            configAction()
            configDataSource()
        }
        
        
    }
    func configRightAndTitle() {
        if self.excuteType == .add || excuteType == .fix {
            self.title = (self.excuteType == .add ? "新增" : "修改") + "竞拍管理"
            let saveBtn = UIBarButtonItem(title: "保存", style: .done, target: self, action: #selector(saveAction))
            
            saveBtn.tintColor = .black
            
            
            self.navigationItem.rightBarButtonItem = saveBtn
        } else {
            self.title = "查看竞拍管理"
            if self.main.zAuditMarkName == "已审核" {
                let saveBtn = UIBarButtonItem(image: UIImage(named: "icon_copy")?.withRenderingMode(.alwaysOriginal), style: .done, target: self, action: #selector(copyAction))
                  saveBtn.tintColor = .black
                 self.navigationItem.rightBarButtonItem = saveBtn
            }
        }
    }
    
    func configView() {
        
        bg.add(item1).add(item2).add(item3).add(item4).add(item5).add(itemProContract).add(item6).add(item7).add(item8).add(item9).add(itemVway).add(item10).add(itemReference).add(item11).add(item12).add(item13).add(item14).add(item15).add(item16).add(item17).add(item18).add(item19).add(item20).add(item21).add(item22).add(item23).add(item24).add(item25).add(item26).add(item27).add(item28).add(item29)
            .addSection(sectionx1)
        
        let viewFlag:ImgViewType = (excuteType == .view) ? .viewOnly : .editable
        imageUtil = KSImageSelectUtil(frame: CGRect(x:0,y:sectionx1.frame.maxY,width:bg.ks_width ,height:imgHeight/2),httpHeader: USERINFO.picUrl.unwrap,maxImgCount: 1,numberOfRow: 5,viewType:viewFlag)
        imageUtil?.ksDelegate = self
        bg.addv(view:imageUtil!)
        self.imageUtil!.newestShow(arr: self.attr_main)
            bg.addSection(sectionx2)
        imageUtil2 = KSImageSelectUtil(frame: CGRect(x:0,y:sectionx2.frame.maxY,width:bg.ks_width ,height:imgHeight/2),httpHeader: USERINFO.picUrl.unwrap,maxImgCount: 3,numberOfRow: 5,picType: [.takePicture,.albumPicture,.albumVideo],viewType:viewFlag)
        imageUtil2.ksDelegate = self
        imageUtil2.u_superVC = self
        bg.addv(view:imageUtil2)
        self.imageUtil2.newestShow(arr: self.attr_detail)

        
        header.ks_height = bg.frame.maxY
        self.tableVw.tableHeaderView = header
    }
    func configAction() {
 
        
        item2.textValueChangeClo = { str in
            self.main.zTitle = str
            
        }
        item4.actionClosure = {
            var allArr = [nameAndModel<String>]()
            for jsonone in
                    ["一元杂","二元杂","三元杂"] {
                let one_x = nameAndModel(shows: [jsonone], model: jsonone)
                allArr.append(one_x)
            }
            let cle:(nameAndModel<String>)->() = { one in
                self.main.zPigType =  one.model
                self.configDataSource()
            }
            let vc = KSSingleSelectUtil.initWithNav(title: "选择", allArr: allArr, backClosure: cle)
            let topViewController = RouterUtils.currentTopViewController()
            topViewController!.present_FullScreen(to: vc)
            
        }
        item5.actionClosure = {
            
            let vc = KSSingleSelectNetUtil()
            vc.title = "选择"
            vc.kSSingleSelectNetNetwork = { page,size,keyword in
                KSNetwork.shared.doRequest(API.homepage(.JPMg_getGoodsNm(name: keyword, page: "\(page)", size: "\(size)"))) { (data:BaseResultOK<JPMGoodsM>) in
                    if data.flag == TRUE {
                        if let infos = data.infos {
                            if page == 1 {
                                vc.allArr.removeAll()
                            }
                            vc.showData(arr:infos)
                        }
                    } else {
                        KSToast("错误")
                    }
                }
            }
            vc.kSSingleSelectNetShowCell = { cell,model in
                
                var contArr:[(String,String?)]!
                 
                
              contArr = [
                ("产品名称:","\((model as! JPMGoodsM).zProductNm.unwrap)")
                ,("产品编码:","\((model as! JPMGoodsM).zProductNo.unwrap)")
                ,("统计名称:","\((model as! JPMGoodsM).zProductAlias.unwrap)")
                 ,("描述:","\((model as! JPMGoodsM).productDescribe.unwrap)")
                ,("计价方式:","\((model as! JPMGoodsM).zUnitNm.unwrap)")
                ,("产品合同名称:","\((model as! JPMGoodsM).productContractNm.unwrap)")
                ,("品种名称:","\((model as! JPMGoodsM).productSaleBree.unwrap)")
 

                       ]
              cell.setDataSource(contentArr: contArr)
               
                 
            }
            vc.backClosure = { model in
                
                self.main.zGoodsNm = (model as! JPMGoodsM).zProductNm.unwrap
                self.main.zProductId = (model as! JPMGoodsM).idKey.unwrap
                self.main.zProductAlias = (model as! JPMGoodsM).zProductAlias.unwrap
                self.main.zProductContractId = (model as! JPMGoodsM).productContractId.unwrap
                self.main.zProductContractNm = (model as! JPMGoodsM).productContractNm.unwrap

                self.main.zValuationWayNm = (model as! JPMGoodsM).zUnitNm.unwrap
                self.main.zValuationWay = (model as! JPMGoodsM).zUnit.unwrap
                self.main.zPigType =  (model as! JPMGoodsM).productSaleBree.unwrap
                self.configDataSource()
                
                
            }
            self.navigationController?.pushViewController(vc,animated:true)
            
            
            
        }
        item6.textValueChangeClo = { str in
            self.main.zNum = str
        }
        item7.textValueChangeClo = { str in
            self.main.zLeastNum = str
        }
        item8.actionClosure = {
            var allArr = [nameAndModel<String>]()
            for jsonone in["50-60","61-70","71-80","81-90","91-100","101-110","111-120","121-130","131-140","141-150","151-160","161-170","171-180","180以上"] {
                let one_x = nameAndModel(shows: [jsonone], model: jsonone)
                allArr.append(one_x)
            }
            let cle:(nameAndModel<String>)->() = { one in
                self.main.zAvgWeight =  one.model
                self.configDataSource()
            }
            let vc = KSSingleSelectUtil.initWithNav(title: "选择", allArr: allArr, backClosure: cle)
            let topViewController = RouterUtils.currentTopViewController()
            topViewController!.present_FullScreen(to: vc)
            
        }
        item9.actionClosure = {
            var allArr = [nameAndModel<String>]()
            for jsonone in["KG","头"] {
                let one_x = nameAndModel(shows: [jsonone], model: jsonone)
                allArr.append(one_x)
            }
            let cle:(nameAndModel<String>)->() = { one in
                self.main.zUnitNm =  one.model
                
                self.configDataSource()
            }
            let vc = KSSingleSelectUtil.initWithNav(title: "选择", allArr: allArr, backClosure: cle)
            let topViewController = RouterUtils.currentTopViewController()
            topViewController!.present_FullScreen(to: vc)
            
        }
        itemVway.actionClosure = {
            let keyValues = valuationWayDic.sorted(by: {$0.0 < $1.0})
            var allArr = [nameAndModel<(key: String, value: String)>]()
            for item in keyValues {
                let one_x = nameAndModel(shows: [item.key], model: item)
                allArr.append(one_x)
            }
            
            let cle:(nameAndModel<(key: String, value: String)>)->() = { one in
                self.main.zValuationWay = one.model.value
                self.main.zValuationWayNm = one.model.key

                self.configDataSource()
             }
            
            let vc = KSSingleSelectUtil.initWithNav(title: "选择", allArr: allArr, backClosure: cle)
            self.present_FullScreen(to: vc)
        }
     
        item10.textValueChangeClo = { str in
            self.main.zPrice = str
        }
       
        item11.textValueChangeClo = { str in
            self.main.zDepositMoney = str
        }
        item12.textValueChangeClo = { str in
            self.main.zRange = str
        }
        item13.textValueChangeClo = { str in
            self.main.zMaxBidNo = str
        }
        item14.actionClosure = {
            self.dateTimePick.resultClosure = { str in
                // 秒都替换为0
                let cutSS = String(str.prefix(str.count - 2) + "00")
                self.main.zBeginDate = cutSS
                self.configDataSource()
            }
            self.dateTimePick.present()
            
        }
        item15.actionClosure = {
            self.dateTimePick.resultClosure = { str in
                // 秒都替换为0
                let cutSS = String(str.prefix(str.count - 2) + "00")
                self.main.zEndDate = cutSS
                self.configDataSource()
            }
            self.dateTimePick.present()
            
        }
        item16.actionClosure = {
            self.dateTimePick.resultClosure = { str in
                // 秒都替换为0
                let cutSS = String(str.prefix(str.count - 2) + "00")
                self.main.zDate = cutSS
                self.configDataSource()
            }
            self.dateTimePick.present()
            
        }
        item17.actionClosure = {
            self.dateTimePick.resultClosure = { str in
                // 秒都替换为0
                let cutSS = String(str.prefix(str.count - 2) + "00")
                self.main.zDateEnd = cutSS
                self.configDataSource()
            }
            self.dateTimePick.present()
            
        }
        item18.actionClosure = {
           
            let vc = KSSingleSelectNetUtil()
            vc.title = "选择"
            vc.kSSingleSelectNetNetwork = { page,size,keyword in
                KSNetwork.shared.doRequest(API.homepage(.JPMg_getOrgNm(name: keyword, page: "\(page)", size: "\(size)"))) { (data:BaseResultOK<JPMOrgM>) in
                    if data.flag == TRUE {
                        if let infos = data.infos {
                            if page == 1 {
                                vc.allArr.removeAll()
                            }
                            vc.showData(arr:infos)
                        }
                    } else {
                        KSToast("错误")
                    }
                }
            }
            vc.kSSingleSelectNetShowCell = { cell,model in
                
                var contArr:[(String,String?)]!
                 
                
              contArr = [
                           ("","\((model as! JPMOrgM).cDeptNmHs.unwrap)")
 //                           ,("","开户行:\((model as! MerchantResult).s_account_bank.unwrap)")
 //                          ,("","账号:\((model as! MerchantResult).s_account_no.unwrap)")


                       ]
              cell.setDataSource(contentArr: contArr)
                
              
                
            }
            vc.backClosure = { model in
                if self.main.zOrgId == (model as! JPMOrgM).cDeptIdHs.unwrap {
                    
                } else {
                    self.main.zOrgNm = (model as! JPMOrgM).cDeptNmHs.unwrap
                    self.main.zOrgId = (model as! JPMOrgM).cDeptIdHs.unwrap
                    self.main.zProvince = (model as! JPMOrgM).cProvince.unwrap
                    self.main.zAddress = (model as! JPMOrgM).cAddress.unwrap
                    self.main.zDeptNm = ""
                    self.main.zDeptId = ""
                    self.main.zCity =  ""
                     self.configDataSource()
                }

                
               
 
            }
            self.navigationController?.pushViewController(vc,animated:true)
            
            
            
        }
        item19.actionClosure = {
            guard self.main.zOrgId.unwrap != "" else {
                KSToast("先选发布单位")
                return
            }
            let vc = KSSingleSelectNetUtil()
            vc.title = "选择"
            vc.kSSingleSelectNetNetwork = { page,size,keyword in
                KSNetwork.shared.doRequest(API.homepage(.JPMg_getDeptNm(name: keyword,org_code: self.main.zOrgId.unwrap, page: "\(page)", size: "\(size)"))) { (data:BaseResultOK<JPDeptM>) in
                    if data.flag == TRUE {
                        if let infos = data.infos {
                            if page == 1 {
                                vc.allArr.removeAll()
                            }
                            vc.showData(arr:infos)
                        }
                    } else {
                        KSToast("错误")
                    }
                }
            }
            vc.kSSingleSelectNetShowCell = { cell,model in
                
                var contArr:[(String,String?)]!
                 
                
              contArr = [
                           ("基地名称","\((model as! JPDeptM).zZcNm.unwrap)")
                            ,("对应部门名称","\((model as! JPDeptM).cDeptName.unwrap)")
 //                          ,("","账号:\((model as! MerchantResult).s_account_no.unwrap)")
 

                       ]
              cell.setDataSource(contentArr: contArr)
                
           
            }
            vc.backClosure = { model in
                self.main.zDeptNm = (model as! JPDeptM).cDeptName.unwrap
                self.main.zDeptId = (model as! JPDeptM).cDeptId.unwrap
                self.main.zZcNm = (model as! JPDeptM).zZcNm.unwrap
                self.main.zZcId = (model as! JPDeptM).zZcId.unwrap
                self.configDataSource()
 
            }
            self.navigationController?.pushViewController(vc,animated:true)
            
            
            
        }
        item20.actionClosure = {
            var allArr = [nameAndModel<String>]()
            for jsonone in provinceFullNameArr {
                let one_x = nameAndModel(shows: [jsonone], model: jsonone)
                allArr.append(one_x)
            }
            let cle:(nameAndModel<String>)->() = { one in
                if self.main.zProvince ==  one.model {
                    
                } else {
                    self.main.zProvince =  one.model
                    self.main.zCity =  ""
                     self.configDataSource()
                }

                
            }
            let vc = KSSingleSelectUtil.initWithNav(title: "选择", allArr: allArr, backClosure: cle)
            let topViewController = RouterUtils.currentTopViewController()
            topViewController!.present_FullScreen(to: vc)
            
        }
        item21.actionClosure = {
            guard self.main.zProvince.unwrap != "" else {
                KSToast("先选省")
                return
            }
            let cityArr = cityFullNameDic[self.main.zProvince.unwrap]!
            var allArr = [nameAndModel<String>]()
            for jsonone in cityArr {
                let one_x = nameAndModel(shows: [jsonone], model: jsonone)
                allArr.append(one_x)
            }
            let cle:(nameAndModel<String>)->() = { one in
                self.main.zCity =  one.model
                self.configDataSource()
            }
            let vc = KSSingleSelectUtil.initWithNav(title: "选择", allArr: allArr, backClosure: cle)
            let topViewController = RouterUtils.currentTopViewController()
            topViewController!.present_FullScreen(to: vc)
            
        }
        item22.textValueChangeClo = {str in
            self.main.zAddress = str
        }
        
        item23.actionClosure = {
           
            let vc = KSSingleSelectNetUtil()
            vc.title = "选择"
            vc.kSSingleSelectNetNetwork = { page,size,keyword in
                KSNetwork.shared.doRequest(API.homepage(.JPMg_getJpName(name: keyword,org_name:"", page: "\(page)", size: "\(size)"))) { (data:BaseResultOK<JPMPersonM>) in
                    if data.flag == TRUE {
                        if let infos = data.infos {
                            if page == 1 {
                                vc.allArr.removeAll()
                            }
                            vc.showData(arr:infos)
                        }
                    } else {
                        KSToast("错误")
                    }
                }
            }
            vc.kSSingleSelectNetShowCell = { cell,model in
                
                var contArr:[(String,String?)]!
                 
                
              contArr = [
                           ("","\((model as! JPMPersonM).orgName.unwrap)")
                            ,("","\((model as! JPMPersonM).cName.unwrap)")
 //                          ,("","账号:\((model as! MerchantResult).s_account_no.unwrap)")


                       ]
              cell.setDataSource(contentArr: contArr)
                
               
            }
            vc.backClosure = { model in
                self.main.zName = (model as! JPMPersonM).cName.unwrap
                self.main.zLinkId = (model as! JPMPersonM).idKey.unwrap

                self.main.zTel = (model as! JPMPersonM).cMobiletel.unwrap

                self.configDataSource()
                
                
            }
            self.navigationController?.pushViewController(vc,animated:true)
            
 
        }
        item24.textValueChangeClo = {str in
            self.main.zTel = str
        }
        item25.segmentChangeClo = { tagx,titlex  in
            self.main.zUse = titlex == "启用" ? "1" : "0"
        }
        item27.segmentChangeClo = { tagx,titlex  in
            self.main.zAutoZb = titlex == "是" ? "1" : "0"
        }
        item28.segmentChangeClo = { tagx,titlex  in
            self.main.zInvited = titlex == "是" ? "1" : "0"
            self.tableVw.reloadData()
        }
        item29.textValueChangeClo = {str in
            self.main.zContent = str
        }
    }
    
    
    func configDataSource() {
        main.zDtradeType = "1"
        item1.setVal(self.main.zRecordNo)
        item2.setVal(self.main.zTitle)
        item3.setVal(TradeDic[self.main.zDtradeType.unwrap])
        item4.setVal(self.main.zPigType)
        item5.setVal(self.main.zGoodsNm)
        itemProContract.setVal(self.main.zProductContractNm)
        item6.setVal(self.main.zNum)
        item7.setVal(self.main.zLeastNum)
        item8.setVal(self.main.zAvgWeight)
        item9.setVal(self.main.zUnitNm)
        itemVway.setVal(self.main.zValuationWayNm)
        if self.main.zUnitNm.unwrap != "" {
            item10.setTempTitle("起拍价(元/\(self.main.zUnitNm.unwrap))*")
            itemReference.setTempTitle("参考价(元/\(self.main.zUnitNm.unwrap))")
        } else {
            item10.setTempTitle("起拍价(元)*")
            itemReference.setTempTitle("参考价(元)")
        }
       
        item10.setVal(self.main.zPrice)
        itemReference.setVal(self.main.referencePrice)
         item11.setVal(self.main.zDepositMoney)
        item12.setVal(self.main.zRange)
        item13.setVal(self.main.zMaxBidNo)
        item14.setVal(self.main.zBeginDate)
        item15.setVal(self.main.zEndDate)
        item16.setVal(self.main.zDate)
        item17.setVal(self.main.zDateEnd)
        item18.setVal(self.main.zOrgNm)
        item19.setVal(self.main.zZcNm)
        item20.setVal(self.main.zProvince)
        item21.setVal(self.main.zCity)
        item22.setVal(self.main.zAddress)
        item23.setVal(self.main.zName)
        item24.setVal(self.main.zTel)
        var v25 = ""
        if self.main.zUse == "0" {
            v25 = "禁用"
        } else if self.main.zUse == "1"  {
            v25 = "启用"
        }
        item25.setSegmentSelectTitle(v25)
        item26.setVal(self.main.zStaffNm)
        var v27 = ""
        if self.main.zAutoZb == "0" {
            v27 = "否"
        } else if self.main.zAutoZb == "1"  {
            v27 = "是"
        }
        item27.setSegmentSelectTitle(v27)
        var v28 = ""
        if self.main.zInvited == "0" {
            v28 = "否"
        } else if self.main.zInvited == "1" {
            v28 = "是"
        }
        item28.setSegmentSelectTitle(v28)
        item29.setVal(self.main.zContent)

    }
    
    
    func dealBeforeAddImages(_ util: KSImageSelectUtil, imgs: [UIImage]) -> [UIImage] {
        return  commonPigWaterMark(imgs: imgs)
    }
    func addImages(_ util: KSImageSelectUtil, imgvideos: [VideoImg]) {
        if util == self.imageUtil {
            self.attr_main += imgvideos
        } else {
            self.attr_detail += imgvideos
        }
        
    }
    func deleteImage(_ util: KSImageSelectUtil, index: Int) {
        
        if util == self.imageUtil {
            let one = self.attr_main[index]
            if one.idkey.unwrap.isEmpty {
                self.attr_main.remove(at: index)
                util.deleteLocalImg(tag: index)
            } else {
                alertUtil(self, title: "确认删除？", operateS: [nameAction(name: "确定", action: { (_) in
                     KSNetwork.shared.doRequest(API.homepage(.JPMg_delPic(id_key: one.idkey.unwrap))) { (data:BaseResult<OperateResult>) in
                        if data.flag == TRUE {
                            KSToast("删除成功")
                            self.attr_main.remove(at: index)
                            util.deleteLocalImg(tag: index)
                        } else {
                            KSToast(data.errorCombine.unwrap)
                        }
                     }

                })])
               
            }
        } else {
            let one = self.attr_detail[index]
            if one.idkey.unwrap.isEmpty {
                self.attr_detail.remove(at: index)
                util.deleteLocalImg(tag: index)
            } else {
                alertUtil(self, title: "确认删除？", operateS: [nameAction(name: "确定", action: { (_) in
                     KSNetwork.shared.doRequest(API.homepage(.JPMg_delPic(id_key: one.idkey.unwrap))) { (data:BaseResult<OperateResult>) in
                        if data.flag == TRUE {
                            KSToast("删除成功")
                            self.attr_detail.remove(at: index)
                            util.deleteLocalImg(tag: index)
                        } else {
                            KSToast(data.errorCombine.unwrap)
                        }
                     }

                })])
               
            }
        }
 
    }
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section != self.details.count {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: JPMgmtFormCell.identifier, for: indexPath) as? JPMgmtFormCell else {
                fatalError()
            }
            
            cell.one = self.details[indexPath.section]
            
            cell.item1.actionClosure = { [indexPath] in
                
                let vc = KSSingleSelectNetUtil()
                vc.title = "选择"
                vc.kSSingleSelectNetNetwork = { page,size,keyword in
                    KSNetwork.shared.doRequest(API.homepage(.JPMg_getClientNm(name: keyword, page: "\(page)", size: "\(size)"))) { (data:BaseResultOK<JPMClientM>) in
                        if data.flag == TRUE {
                            if let infos = data.infos {
                                if page == 1 {
                                    vc.allArr.removeAll()
                                }
                                vc.showData(arr:infos)
                            }
                        } else {
                            KSToast("错误")
                        }
                    }
                }
                vc.kSSingleSelectNetShowCell = { cell,model in
                    
                    var contArr:[(String,String?)]!
                     
                    
                  contArr = [
                               ("","客户：\((model as! JPMClientM).clientDesc.unwrap)")
                                ,("","公司：\((model as! JPMClientM).orgName.unwrap)")
     //                          ,("","账号:\((model as! MerchantResult).s_account_no.unwrap)")


                           ]
                  cell.setDataSource(contentArr: contArr)
                    
                     
                    
                }
                vc.backClosure = {[indexPath] model in
                     self.details[indexPath.section].clientDesc = (model as! JPMClientM).clientDesc.unwrap
                    self.details[indexPath.section].orgName = (model as! JPMClientM).orgName.unwrap
                    self.details[indexPath.section].clientName = (model as! JPMClientM).accountName.unwrap
                 self.details[indexPath.section].tel = (model as! JPMClientM).tel.unwrap
 
                     
                    self.tableVw.reloadData()
                    
                    
                }
                self.navigationController?.pushViewController(vc,animated:true)
                
                
                
            }
            
            return cell
        }  else  {  // +
            let cell = tableView.dequeueReusableCell(withIdentifier: GlobalAddTableCell.identifier, for: indexPath) as! GlobalAddTableCell
            cell.titleLab.text = "+  添加"
            return cell
        }
        
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        if self.main.zInvited == "1" {
            return self.details.count + 1
        } else {
            return 0
        }
        
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == self.details.count {
            return 1
        } else {
            if self.details[section].openx == true {
                return 1
            } else {
                return 0
            }
        }
        
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == self.details.count {
            
            let one = ClientInfo(JSON: ["" : ""])!
            self.details.append(one)
            self.configDataSource()
            self.tableVw.reloadData()
            
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == self.details.count  {
            return 40
        }   else {
            return 150
            
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == self.details.count {
            return 0
        } else {
            return 40
        }
        
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        
        
        guard let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: GlobalSectionHeader.identifier) as? GlobalSectionHeader else {
            fatalError()
        }
        let tap = UITapGestureRecognizer()
        tap.numberOfTapsRequired = 1
        tap.addTap { [unowned self] _ in
            self.details[section].openx = !self.details[section].openx
            let set = IndexSet(integer:section)
            tableView.reloadSections(set, with:UITableView.RowAnimation.automatic)
            
        }
        
        headerView.addGestureRecognizer(tap)
        
        
        if self.excuteType == .add  || self.excuteType == .fix {
            headerView.deleteClo = {
                alertUtil(self, title: "确认删除？", operateS: [nameAction(name: "确定", action: { (_) in
                    self.details.remove(at: section)
                    self.countSum()
                    self.configDataSource()
                    self.tableVw.reloadData()
                })])
                
            }
            headerView.delBtn.isHidden = false
        } else {
            headerView.delBtn.isHidden = true
        }
        
        
        headerView.setOpenx(flag: self.details[section].openx)

     
        
        
        headerView.setTitle("邀拍明细\(section + 1)")
        return headerView
        
        
    }
    func countSum() {
        //        let sum = self.details.compactMap { doubleTran($0.zPlanNum) }.reduce(0, +)
        //        self.main.zNum = "\(sum.roundTo(0))"
    }
    
    // MARK: - 提交
    @objc func copyAction() {
        alertUtil(self, title: "确定复制当前记录？", operateS: [nameAction(name: "确定", action: { _ in
            self.main.zAuditMarkName = "未提交"
            self.main.zAuditMark = "0"
            self.main.idNew = self.main.idKey
            self.main.idKey = ""
            self.excuteType = .add
            self.attr_main.removeAll()
            self.attr_detail.removeAll()
            self.imageUtil!.newestShow(arr: self.attr_main)
             self.imageUtil2.newestShow(arr: self.attr_detail)
            let viewFlag:ImgViewType = (self.excuteType == .view) ? .viewOnly : .editable
            self.imageUtil!.viewType = viewFlag
            self.imageUtil2.viewType = viewFlag

            
            self.configRightAndTitle()
        })])
    }
    @objc func saveAction() {
        
        guard self.judgeNoNone() else {
            return
        }
         let vali = Validation()
        
        vali.expression(doubleTran(self.main.zLeastNum) <= doubleTran(self.main.zNum) , msg: "起拍数量不能大于数量")
 
        vali.expression(self.main.zBeginDate.unwrap < self.main.zEndDate.unwrap, msg: "结束时间必须大于开始时间")
        vali.expression(self.main.zDate.unwrap < self.main.zDateEnd.unwrap, msg: "出栏时间（结束）必须大于出栏时间（开始）")

        if self.main.zInvited == "1" {
          
            for i in 0..<self.details.count {
                   vali.required(value: self.details[i].clientDesc, msg: "第\(i + 1)条细表，客户不能为空!")
             }
     
        }
        
        guard vali.validate() else {
            return
        }

        
        let masterjson = dictionaryToJson(self.main.dictionaryRepresentation())
        
        var dataJson = ""
        if self.main.zInvited == "1" {
            let detailsss = self.details.compactMap { dictionaryToJson($0.dictionaryRepresentation()) }.joined(separator: ",")
            dataJson = "[" + detailsss + "]"
        } else {
            dataJson = "[]"
        }
 
        // 有附件就传
        
        let unUploadM = self.attr_main.filter{ $0.idkey.unwrap == "" }
        let unUploadD = self.attr_detail.filter{ $0.idkey.unwrap == "" }
        
        dealVideoData(arr: unUploadD) { arr in
            var api:API?
            if self.excuteType == .fix {
                api = API.homepage(.JPMg_updateJpInfo(data: masterjson, detail: dataJson, files: unUploadM,newFiles: arr))
            } else {
                api = API.homepage(.JPMg_saveJpInfo(data: masterjson, detail: dataJson, files: unUploadM,newFiles: arr))
            }
            
             KSNetwork.shared.doRequest(api!) {[weak self] (data:BaseResultOK<OperateResult>) in
                guard let `self` = self else { return }
                if data.flag == TRUE {
                    KSToast("保存单据成功")
                    self.backAction()
                 } else {
                     KSToast(data.errorCombine.unwrap)
                 }
            }
        }
 
        
    }
 
 
    func backAction() {
        if let clo = self.refreshClosure {
            clo()
        }
        self.navigationController?.popViewController(animated: true)
    }
    
    
    
}
